<template>
  <div>
    <a-form>
      <a-card style="margin-top: 20px">
        <div class="title_detail">分拣</div>
        <div class="">
          <div>单价直接打印页面</div>
          <a-button type="primary" @click="goDetail('add', null)">
            补打唯一码
          </a-button>
        </div>
        <a-form-item
          label="唯一码"
          :labelCol="{ span: 4 }"
          :wrapperCol="{ span: 4 }"
          required
        >
          <a-input
            v-model="detailForm.title"
            placeholder="请输入商品标题"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="分拣库位"
          :labelCol="{ span: 4 }"
          :wrapperCol="{ span: 4 }"
          required
        >
          <a-input
            v-model="detailForm.title"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="订单已入库"
          :labelCol="{ span: 4 }"
          :wrapperCol="{ span: 4 }"
          required
        >
          <a-input
            v-model="detailForm.title"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="当前商品SPU/中文名"
          :labelCol="{ span: 4 }"
          :wrapperCol="{ span: 4 }"
          required
        >
          <a-input
            v-model="detailForm.title"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="当前商品SKU"
          :labelCol="{ span: 4 }"
          :wrapperCol="{ span: 4 }"
          required
        >
          <a-input
            v-model="detailForm.title"
          ></a-input>
        </a-form-item>
      </a-card>
    </a-form>
  </div>
</template>
  <script>
import Editor from "@/comps/Editor";
import { deepCopy } from "@/utils/util";
import UploadImg from "@/comps/UploadImg.vue";
import { baseTemplate } from "@/api/logistic";
import {
  attributeValue,
  categoryTree,
  productDetail,
  productAdd,
} from "@/api/product";
export default {
  components: { Editor, UploadImg },
  data() {
    return {
      form: this.$form.createForm(this, { name: "addProd" }),
      editorDetl: "",
      hasLoaded: false,
      pageType: "add",
      productId: "",
      detailForm: {
        title: "",
        name: "",
        cnName: "",
        predictionName: "",
        categoryId: "",
        spuCode: "",
        sort: 0,
        mainImg: "",
        subImg: "",
        detailImg: "",
        videoUrl: "",
        tmplCode: "",
      },
      templateList: [],
      AllAttributes: [],
      afterHandleAttrData: [],
      colorLists: [],
      selectColor: [],
      sizeLists: [],
      selectSize: [],
      shoeLists: [],

      categoryTreeData: [],
      skuColumns: [
        { title: "批量填充", scopedSlots: { customRender: "index" } },
        { title: "color-all", scopedSlots: { customRender: "color" } },
        { title: "size-all", scopedSlots: { customRender: "size" } },
        { title: "SkuCode", scopedSlots: { customRender: "skuCode" } },
        { title: "采购成本", scopedSlots: { customRender: "cost" } },
        { title: "线上价格", scopedSlots: { customRender: "onlinePrice" } },
        { title: "线下价格", scopedSlots: { customRender: "offlinePrice" } },
        { title: "是否下架", scopedSlots: { customRender: "status" } },
        { title: "重量(kg)", scopedSlots: { customRender: "weight" } },
        { title: "体积(cm^3)", scopedSlots: { customRender: "volume" } },
      ],
      originSkuList: [],
      skuLists: [],
    };
  },
  async created() {
    let { type = "add", id = "" } = this.$route.query;
    this.pageType = type;
    this.productId = id;
    await this.getBaseTemplate();
    await this.getCategoryList();
    await this.getAttributeVals();
  },
  async mounted() {
    if (this.pageType == "edit") {
      await this.getDetail(this.productId);
    } else {
      this.hasLoaded = true;
    }
  },
  computed: {},

  methods: {
    async getBaseTemplate() {
      let res = await baseTemplate();
      this.templateList = res?.data;
    },
    async getDetail(id) {
      let res = await productDetail(id);
      let {
        title = "",
        name = "",
        cnName = "",
        predictionName = "",
        categoryId = "",
        description = "",
        spuCode = "",
        sort = 0,
        mainImg = "",
        subImg = "",
        detailImg = "",
        videoUrl = "",
        tmplCode = "",
        skus = [],
        attrValues = [],
      } = res?.data;
      this.detailForm = {
        title,
        name,
        cnName,
        predictionName,
        categoryId,
        spuCode,
        sort,
        mainImg,
        subImg: subImg?.[0] == "" ? "" : subImg,
        detailImg: detailImg?.[0] == "" ? "" : detailImg,
        videoUrl: videoUrl?.[0] == "" ? "" : videoUrl,
        tmplCode,
      };
      this.editorDetl = description;

      this.hasLoaded = true;
      this.afterHandleAttrData = attrValues;
      let choosedColors = [],
        choosedSizes = [];
      let temChildrenColor = attrValues.filter((item) => {
          return item.name == "Color";
        }),
        temChildrenSize = attrValues.filter((item) => {
          return item.name == "Size";
        });
      for (let j = 0; j < temChildrenColor[0].values.length; j++) {
        choosedColors.push(temChildrenColor[0].values[j].id);
      }
      // console.log("choosedSizes-->>", temChildrenSize);
      for (let k = 0; k < temChildrenSize[0].values.length; k++) {
        choosedSizes.push(temChildrenSize[0].values[k].id);
      }
      this.selectSize = choosedSizes;
      this.selectColor = choosedColors;
      this.skuLists = skus.map((item, idx) => {
        if (item) {
          let info = {
            ...item,
          };

          info.status = item.status == 1;
          info.sort = idx + 1;
          info.color = this.getAttrs(item.attrValues, "Color");
          info.size = this.getAttrs(item.attrValues, "Size");
          return info;
        }
      });
      this.originSkuList = this.skuLists;
    },
    getNewArribute(ids, type) {
      let allList = this.AllAttributes.filter((item) => {
          return item.name == type;
        }),
        temValues = allList[0].values;
      let deslist = temValues.filter((item) => {
        return ids.includes(item.id);
      });
      this.afterHandleAttrData[type == "Size" ? 1 : 0] = {
        ...allList[0],
        values: deslist,
      };
    },
    // 组合属性
    attrCombination(ids, type) {
      this.getNewArribute(ids, type);
      let sizeArr = this.afterHandleAttrData[1];
      let colorArr = this.afterHandleAttrData[0];
      let attrValues = [];
      if (!this.selectColor.length || !this.selectSize.length) {
        this.skuLists = [];
        this.originSkuList = [];
        return;
      }
      if (sizeArr?.values?.length && colorArr?.values?.length) {
        for (let i = 0; i < sizeArr.values.length; i++) {
          for (let j = 0; j < colorArr.values.length; j++) {
            attrValues.push({
              attrId: colorArr.values[j].id + "_" + sizeArr.values[i].id,
              attrValues: [
                {
                  ...colorArr,
                  values: [colorArr.values[j]],
                },
                {
                  ...sizeArr,
                  values: [sizeArr.values[i]],
                },
              ],
            });
          }
        }
      }
      let hasIds = [];
      let originSkuList = JSON.parse(JSON.stringify(this.originSkuList));
      if (originSkuList?.length) {
        for (let i = 0; i < originSkuList.length; i++) {
          let attrArr = originSkuList[i].attrValues;
          let id = "";
          for (let j = 0; j < attrArr.length; j++) {
            for (let p = 0; p < attrArr[j].values.length; p++) {
              id += ((j == 1 && "_") || "") + attrArr[j].values[p].id;
            }
          }
          id && hasIds.push(id);
        }
      }
      attrValues = attrValues.filter((f) => !hasIds.includes(f.attrId));

      for (let i = 0; i < attrValues.length; i++) {
        originSkuList.push({
          cost: "",
          id: "",
          offlinePrice: "",
          onlinePrice: "",
          skuCode: "",
          spuCode: this.detailForm.spuCode,
          status: false,
          volume: "",
          weight: "",
          attrValues: attrValues[i].attrValues,
        });
      }
      // this.skuLists = originSkuList;
      this.skuLists = originSkuList.map((item, idx) => {
        if (item) {
          let info = {
            ...item,
          };
          info.status = item.status == 1;
          info.sort = idx + 1;
          info.size = this.getAttrs(item.attrValues, "Size");
          info.color = this.getAttrs(item.attrValues, "Color");
          return info;
        }
      });
      // console.log("skuLists>>>>>", this.skuLists);
    },
    colorSelectChange(ids) {
      this.attrCombination(ids, "Color");
    },
    sizeSelectChange(ids) {
      this.attrCombination(ids, "Size");
    },
    async getAttributeVals() {
      let res = await attributeValue({ type: 0 }),
        temList = res?.data,
        temColor = [],
        temSize = [],
        temShoe = [];
      for (let j = 0; j < temList.length; j++) {
        if (temList[j].name == "Size") {
          temSize = temList[j].values;
        }
        if (temList[j].name == "Color") {
          temColor = temList[j].values;
        }
        if (temList[j].name == "Shoe size") {
          temShoe = temList[j].values;
        }
      }
      this.AllAttributes = temList;
      this.colorLists = temColor;
      this.sizeLists = temSize;
      this.shoeLists = temShoe;
    },
    deleteNull(arr) {
      let list = [];
      arr.map((item) => {
        if (item.children == null) {
          delete item.children;
        } else {
          item.children = this.deleteNull(item.children);
        }
        list.push(item);
      });
      return list;
    },
    async getCategoryList() {
      let res = await categoryTree(),
        temList = res?.data;
      this.categoryTreeData = this.deleteNull(temList);
      // console.log("catory tree", this.categoryTreeData);
    },
    getAttrs(list, type) {
      // console.log('list',list,type)
      if (type == "Sort") {
        let tem = list.filter((item) => {
          return item.name == "Size";
        });
        return tem[0]?.values?.[0]?.sort;
      } else {
        let tem = list.filter((item) => {
            return item.name == type;
          }),
          tes = tem[0]?.values?.[0];
        return type == "Color" ? JSON.parse(tes?.value)?.rgbValue : tes?.value;
      }
    },
    editorChange(html) {
      this.editorDetl = html;
    },
    async save() {
      let form = deepCopy(this.detailForm);
      // console.log("form", form, this.afterHandleAttrData);
      if (this.skuLists.length == 0) {
        return this.$message.error("请添加商品SKU");
      }
      let temList = deepCopy(this.skuLists);
      for (let i = 0; i < temList.length; i++) {
        temList[i].status = temList[i].status ? 1 : 0;
        delete temList[i].color;
        delete temList[i].size;
      }

      let temSubImg = [],
        temDetailImg = [],
        temVideoUrl = [];
      if (!Array.isArray(form.detailImg)) {
        if (form.detailImg != "") {
          temDetailImg.push(form.detailImg);
        } else {
          temDetailImg = [];
        }
      } else {
        temDetailImg = form.detailImg;
      }
      if (!Array.isArray(form.subImg)) {
        if (form.subImg != "") {
          temSubImg.push(form.subImg);
        } else {
          temSubImg = [];
        }
      } else {
        temSubImg = form.subImg;
      }
      if (!Array.isArray(form.videoUrl)) {
        if (form.videoUrl != "") {
          temVideoUrl.push(form.videoUrl);
        } else {
          temVideoUrl = [];
        }
      } else {
        temVideoUrl = form.videoUrl;
      }
      try {
        productAdd({
          ...form,
          skus: temList,
          attrValues: this.afterHandleAttrData,
          description: this.editorDetl,
          subImg: temSubImg,
          detailImg: temDetailImg,
          videoUrl: temVideoUrl,
          id: this.productId,
        }).then((res) => {
          if (res?.success) {
            this.$message.success("保存成功");
            this.$router.replace({ path: "/product/list" });
          } else this.$message.error(res?.message);
        });
      } catch (e) {
        console.log(e);
      }
    },
  },
};
</script>
  <style scoped>
.title_detail {
  font-size: 20px;
  font-weight: 500;
  color: #000;
  margin-bottom: 20px;
}
.img_title {
  width: 100px;
  text-align: center;
}
.title_part {
  font-size: 16px;
  font-weight: 500;
  color: #000;
  margin: 12px 0;
}
</style>
  